package com.mengrv.springbootdemo.service.Impl;

import com.mengrv.springbootdemo.model.User;
import com.mengrv.springbootdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int postUser(User user) {
        return jdbcTemplate.update(
                "insert into user(userID, account, userName, birthday, password, positionCode) VALUES (?,?,?,?,?,?)",
                user.getUserID(), user.getAccount(), user.getUserName(), user.getBirthday(), user.getPassword(), user.getPositionCode()
        );
    }

    @Override
    public void deleteByAccount(String account) {
        jdbcTemplate.update("delete from user where account = ?", account);
    }

    @Override
    public User getUserByToken(String token) {
        List<User> list = jdbcTemplate.query("select * from user where token = ?", new Object[]{token}, new BeanPropertyRowMapper(User.class));
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public User getUserByAccount(String account) {
        List<User> list = jdbcTemplate.query("select * from user where account = ?", new Object[]{account}, new BeanPropertyRowMapper(User.class));
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public List<User> getUserList(int offset, int limit) {
        List<User> list = jdbcTemplate.query("select * from user limit ?,?", new Object[]{offset, limit}, new BeanPropertyRowMapper(User.class));
        return list;
    }

    @Override
    public void updateToken(String token, String userID) {
        jdbcTemplate.update("update user set token = ? where userID = ?", token, userID);
    }

    @Override
    public void updatePasswordByAccount(String account, String password) {
        jdbcTemplate.update("update user set password = ? where account = ?", password, account);
    }

    @Override
    public int updateUserInfo(User user) {
        return jdbcTemplate.update("update user set birthday = ?, userName = ?, mobile = ? where account = ?", user.getBirthday(), user.getUserName(), user.getMobile(), user.getAccount());
    }
}
